package GameServer.manager.event;

import GameServer.Demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by gzhd on 2017/11/29.
 *
 * 事件处理器
 */
public class EventMgr implements Runnable {
    public static Map<Integer,List<EventProc>> procs;
//    用于数据交换
    public static BlockingQueue<Event> queue = new LinkedBlockingDeque<>();
    public volatile boolean work;
    public static EventMgr inst;
    private static  Event exit=new Event();

    private EventMgr(){
        inst = this;
    }

    @Override
    public void run() {
//        处理事件
        while (work) {
            Event evt = null;
            try {
//                不断从队列里面抽出来处理
                evt = queue.take();
            } catch (InterruptedException e) {
               Demo.print( "Exception when take" + evt);
                continue;
            } finally {

            }
            if (evt == exit) {
                break;
            }
            List<EventProc> list = procs.get(evt.id);
            if (list == null) {
                Demo.print("该事件id:"+evt.id+",没有注册过");
                continue;
            }
            int size = list.size();
            for (int i = 0; i < size; i++) {
                EventProc proc = list.get(i);
                if (proc.disable) {
                    continue;
                }

                try {
                    proc.proc(evt);
                } catch (Throwable t) {
                    Demo.print("处理事件导常"+evt.id+" ");

                } finally {
                }
            }

        }
        Demo.print("结束事件处理器");
    }

    public static EventMgr getInstance(){
        if (inst == null) {
            inst = new EventMgr();

        }
        return inst;
    }

    public void init(){
        procs = new HashMap<Integer, List<EventProc>>();
        work=true;
        new Thread(this, "EventMgr").start();
        Demo.print("事件处理器启动成功");
    }


    public static void shutdown(){
        queue.add(exit);
    }

    public static void addEvent(int id,Object parm){
        Event evt = new Event();
        evt.id=id;
        evt.parm = parm;
        queue.add(evt);
    }

    public static void regist(int id,EventProc proc){
        List<EventProc> list = procs.get(id);
        if (list == null) {
            list = new ArrayList<EventProc>(1);
            procs.put(id, list);
        }
        list.add(proc);
    }


}
